<?php

namespace App\Services\ResetUserPassword;

use Closure;
use App\Models\User;
use App\Supports\Sms\Sms;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Illuminate\Support\Facades\Log;

class ResetUserPasswordRequest extends FormRequest
{
	protected User $user;

	public function rules(): array
	{
		return [
			'phone' => 'required|phone:CN,mobile',
			'sms_key' => 'required|string',
			'sms_code' => ['required', 'string', $this->smsCode()],
			'password' => 'required|alpha_dash|min:6|max:20',
		];
	}

	public function attributes(): array
	{
		return [
			'sms_key' => '短信验证码密钥',
			'sms_code' => '短信验证码',
		];
	}

	public function smsCode(): Closure
	{
		return function ($key, $value, $fail) {
			$sms = app(Sms::class);
			if ($sms->isSmsDataRight($this->sms_key, $this->phone, $this->sms_code)) {
				if (!$user = User::firstWhere('phone', $this->phone)) {
					return $fail('账号不存在');
				}
				$this->user = $user;
				$sms->cleanCachedDataAfterUsing($this->sms_key);
			} else {
				return $fail('短信验证码无效');
			}
			return true;
		};
	}

	public function getUser(): User
	{
		return $this->user;
	}
}
